<?php
namespace app\admin\controller;

use think\Controller;
use Common\Controller\BaseController;
use think\Model;
use think\Request;
use think\Session;
defined('EBusinessID') or define('EBusinessID', '1447530');
//电商加密私钥，快递鸟提供，注意保管，不要泄漏
defined('APIKey') or define('APIKey', '78938dd0-adba-4dc8-9a68-7f3ec6e7efa3');

class Dayin extends Controller
{
    public function index()
    {

        $id['id'] = $_GET['id'];
        $res=db('user')->where($id)->find();
        //dump($res);exit;
        //电商ID
        defined('EBusinessID') or define('EBusinessID', '1447530');
//电商加密私钥，快递鸟提供，注意保管，不要泄漏
        defined('AppKey') or define('AppKey', '78938dd0-adba-4dc8-9a68-7f3ec6e7efa3');
//请求url，正式环境地址：http://api.kdniao.com/api/Eorderservice    测试环境地址：http://testapi.kdniao.com:8081/api/EOrderService
        //defined('ReqURL') or define('ReqURL', 'http://testapi.kdniao.com:8081/api/Eorderservice');
        defined('ReqURL') or define('ReqURL', 'http://api.kdniao.com/api/Eorderservice');
//批量打印接口地址
        defined('API_URL') or define('API_URL', 'http://www.kdniao.com/External/PrintOrder.aspx');
//IP服务地址
        defined('IP_SERVICE_URL') or define('IP_SERVICE_URL','http://www.kdniao.com/External/GetIp.aspx');
        //电商加密私钥，快递鸟提供，注意保管，不要泄漏
        defined('APIKey') or define('APIKey','78938dd0-adba-4dc8-9a68-7f3ec6e7efa3');
/*
        //构造电子面单提交信息
        $eorder = [];
        $eorder["ShipperCode"] = "SF";
        $eorder["OrderCode"] = "0126577003879";
        $eorder["PayType"] = 1;
        $eorder["ExpType"] = 1;
//发货姓名
        $sender = [];
        $sender["Name"] = $res['hairname'];
        $sender["Mobile"] = $res['hairphone'];
        $sender["ProvinceName"] = $res['hairname'];
        $sender["CityName"] = $res['haircity'];
        $sender["ExpAreaName"] = $res['hairaddress'];
        $sender["Address"] = $res['haircompany'];
//收货姓名
        $receiver = [];
        $receiver["Name"] = $res["collectname"];
        $receiver["Mobile"] = $res['collectphone'];
        $receiver["ProvinceName"] = $res['collectname'];
        $receiver["CityName"] = $res['collectcity'];
        $receiver["ExpAreaName"] = $res['collectaddress'];
        $receiver["Address"] = $res['collectompany'];

        $commodityOne = [];
        $commodityOne["GoodsName"] = "其他";
        $commodity = [];
        $commodity[] = $commodityOne;

        $eorder["Sender"] = $sender;
        $eorder["Receiver"] = $receiver;
        $eorder["Commodity"] = $commodity;
*/
//dump($eorder);exit;
        //构造电子面单提交信息
        $eorder = [];
        $eorder["ShipperCode"] = "EMS";
        $eorder["OrderCode"] = "012657700386";
        $eorder["PayType"] = 1;
        $eorder["ExpType"] = 1;

        $sender = [];
        $sender["Name"] = "李先生";
        $sender["Mobile"] = "18888888888";
        $sender["ProvinceName"] = "李先生";
        $sender["CityName"] = "深圳市";
        $sender["ExpAreaName"] = "福田区";
        $sender["Address"] = "赛格广场5401AB";

        $receiver = [];
        $receiver["Name"] = "李先生";
        $receiver["Mobile"] = "18888888888";
        $receiver["ProvinceName"] = "李先生";
        $receiver["CityName"] = "深圳市";
        $receiver["ExpAreaName"] = "福田区";
        $receiver["Address"] = "赛格广场5401AB";

        $commodityOne = [];
        $commodityOne["GoodsName"] = "其他";
        $commodity = [];
        $commodity[] = $commodityOne;

        $eorder["Sender"] = $sender;
        $eorder["Receiver"] = $receiver;
        $eorder["Commodity"] = $commodity;

//调用电子面单
        $jsonParam = json_encode($eorder, JSON_UNESCAPED_UNICODE);

//$jsonParam = JSON($eorder);//兼容php5.2（含）以下

        echo "电子面单接口提交内容：<br/>" . $jsonParam;
        $jsonResult = $this->submitEOrder($jsonParam);
        echo "<br/><br/>电子面单提交结果:<br/>" . $jsonResult;

//解析电子面单返回结果
        $result = json_decode($jsonResult, true);
        echo "<br/><br/>返回码:" . $result["ResultCode"];
        if ($result["ResultCode"] == "100") {
//            dump($result);exit;
            //$this->build_form($result['Order']['OrderCode']);
//            dump($from);exit;
           // echo "<br/>是否成功:" . $result["Success"];
            echo"<script>alert('电子面单下单成功');location.href='../../../admin/index/express';</script>";
        //return $from;
            //return $result;
            //dump($result);exit;
        } else {
            echo"<script>alert('电子面单下单失败');</script>";
            //echo "<br/>电子面单下单失败";
            //dump($result);exit;
        }
//-------------------------------------------------------------


        /**
         * Json方式 调用电子面单接口
         */


        /**
         *  post提交数据
         * @param  string $url 请求Url
         * @param  array $datas 提交的数据
         * @return url响应返回的html
         */
    }
        public function sendPost($url, $datas)
        {
            $temps = array();
            foreach ($datas as $key => $value) {
                $temps[] = sprintf('%s=%s', $key, $value);
            }
            $post_data = implode('&', $temps);
            $url_info = parse_url($url);
            if (empty($url_info['port'])) {
                $url_info['port'] = 80;
            }
            $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
            $httpheader .= "Host:" . $url_info['host'] . "\r\n";
            $httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
            $httpheader .= "Content-Length:" . strlen($post_data) . "\r\n";
            $httpheader .= "Connection:close\r\n\r\n";
            $httpheader .= $post_data;
            $fd = fsockopen($url_info['host'], $url_info['port']);
            fwrite($fd, $httpheader);
            $gets = "";
            $headerFlag = true;
            while (!feof($fd)) {
                if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                    break;
                }
            }
            while (!feof($fd)) {
                $gets .= fread($fd, 128);
            }
            fclose($fd);

            return $gets;
        }

        /**
         * 电商Sign签名生成
         * @param data 内容
         * @param appkey Appkey
         * @return DataSign签名
         */


    public function encrypt($data, $appkey)
    {
        return urlencode(base64_encode(md5($data . $appkey)));
    }
    /**************************************************************
     *
     *  使用特定function对数组中所有元素做处理
     * @param  string &$array 要处理的字符串
     * @param  string $function 要执行的函数
     * @return boolean $apply_to_keys_also     是否也应用到key上
     * @access public
     *
     *************************************************************/

    public function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
        {
            static $recursive_counter = 0;
            if (++$recursive_counter > 1000) {
                die('possible deep recursion attack');
            }
            foreach ($array as $key => $value) {
                if (is_array($value)) {
                    $this->arrayRecursive($array[$key], $function, $apply_to_keys_also);
                } else {
                    $array[$key] = $function($value);
                }

                if ($apply_to_keys_also && is_string($key)) {
                    $new_key = $function($key);
                    if ($new_key != $key) {
                        $array[$new_key] = $array[$key];
                        unset($array[$key]);
                    }
                }
            }
            $recursive_counter--;
        }


        /**************************************************************
         *
         *  将数组转换为JSON字符串（兼容中文）
         *  @param  array   $array      要转换的数组
         *  @return string      转换得到的json字符串
         *  @access public
         *
         *************************************************************/
       public function JSON($array) {
           $this->arrayRecursive($array, 'urlencode', true);
            $json = json_encode($array);
            return urldecode($json);
        }


    public function submitEOrder($requestData){
        $datas = array(
            'EBusinessID' => '1447530',
            'RequestType' => '1007',
            'RequestData' => urlencode($requestData),
            'DataType' => '2',
        );

        $datas['DataSign'] = $this->encrypt($requestData,'78938dd0-adba-4dc8-9a68-7f3ec6e7efa3');
        $result = $this->sendPost(ReqURL,$datas);
        //根据公司业务处理返回的信息......
//        dump($result);exit;
        return $result;
    }

public function build_form($result) {

    $request_data = [['OrderCode'=>$result,'PortName'=>'Microsoft Shared Fax Driver']];
    //OrderCode:需要打印的订单号，和调用快递鸟电子面单的订单号一致，PortName：本地打印机名称，请参考使用手册设置打印机名称。支持多打印机同时打印。
//    $request_data = '[{"OrderCode":"'.$result.'","PortName":"LS--20161121XNE Samsung SCX-3400 Series"}]';
    $request_data = $this->JSON($request_data);
//    dump($request_data);exit;
    $request_data_encode = urlencode($request_data);
    $data_sign = $this->encrypt($this->get_ip().$request_data_encode, APIKey);
    //是否预览，0-不预览 1-预览
    $is_priview = '0';
   //dump($this->get_ip());exit;
//var_dump($request_data,API_URL,EBusinessID,$data_sign,$is_priview);exit;
    //组装表单
        $form = '<form id="form1" method="POST" action="'.API_URL.'"><input type="text" name="RequestData" value="'.$request_data.'"/><input type="text" name="EBusinessID" value="'.EBusinessID.'"/><input type="text" name="DataSign" value="'.$data_sign.'"/><input type="text" name="IsPriview" value="'.$is_priview.'"/></form><script>form1.submit();</script>';
        print_r($form);

}
    /**
     * 判断是否为内网IP
     * @param ip IP
     * @return 是否内网IP
     */
   public function is_private_ip($ip) {
        return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
    }

    /**
     * 获取客户端IP(非用户服务器IP)
     * @return 客户端IP
     */
   public function get_ip() {
        //获取客户端IP
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        if(!$ip || $this->is_private_ip($ip)) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, IP_SERVICE_URL);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);

            return $output;
        }
        else{
            return $ip;
        }
    }

}